package com.yjt.fresh.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.adpater.adpsection.AdpRvAtyCart;
import com.yjt.fresh.adpater.adpsection.OnSectionItemClickListener;
import com.yjt.fresh.adpater.adpsection.SectionedSpanSizeLookup;
import com.yjt.fresh.api.ApiDeleteBuyCart;
import com.yjt.fresh.api.ApiGetCartList;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanCart;
import com.yjt.fresh.bean.BeanCartChange;
import com.yjt.fresh.bean.MessageEvent;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToastResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 购物车
 * Created by mcc on 2018-07-30.
 */

public class AtyCart extends BaseSimpleActivity {

    private static final int REQUEST_CODE = 1006;
    private static final int REFRESH_RV = 10007;
    @BindView(R.id.back)
    RelativeLayout mBack;
    @BindView(R.id.rvAppAtyCart)
    RecyclerView mRv;
    @BindView(R.id.cbAppAtyCartSelectAll)
    CheckBox mCbSelectAll;
    @BindView(R.id.tvAtyCartSettleAccount)
    TextView mTvSettleAccount;
    @BindView(R.id.tvAppAtyCartNeedMoney)
    TextView mTvNeedMoney;
    @BindView(R.id.tvAppAtyCartEdit)
    TextView mTvEdit;
    @BindView(R.id.tvAppAtyCartCancel)
    TextView mTvCancel;
    @BindView(R.id.tvAtyCartDelete)
    TextView mTvDelete;
    @BindView(R.id.flAppAtyCartRight)
    FrameLayout mFlRight;
    @BindView(R.id.llAppAtyCartNeedMoney)
    LinearLayout mLlNeedMoney;

    private List<BeanCartChange> mBeanCartChanges = new ArrayList<>();
    private AdpRvAtyCart mAdpRvAtyCart;
    private int mSelectCount;
    private ArrayList<String> mBuyCartIDs = new ArrayList<>();
    private double mNeedMoney;
    private List<BeanCartChange> mChanges;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_cart;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initEvent() {
        initRv();
        EventBus.getDefault().register(this);
        getData();
        initClick();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent e){
        if (e.getRecode() == REFRESH_RV){
            mAdpRvAtyCart.notifyDataSetChanged();
        }
    }

    private void initClick() {
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTvEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvEdit.setVisibility(View.GONE);
                mTvCancel.setVisibility(View.VISIBLE);
                mLlNeedMoney.setVisibility(View.GONE);
                mTvSettleAccount.setVisibility(View.GONE);
                mTvDelete.setVisibility(View.VISIBLE);
            }
        });

        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvEdit.setVisibility(View.VISIBLE);
                mTvCancel.setVisibility(View.GONE);
                mLlNeedMoney.setVisibility(View.VISIBLE);
                mTvSettleAccount.setVisibility(View.VISIBLE);
                mTvDelete.setVisibility(View.GONE);
            }
        });
        mTvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectCount == 0) {
                    Toast.makeText(mContext, "请先选择要删除的商品", Toast.LENGTH_SHORT).show();
                } else {
                    deleteDialog();
                }
            }
        });

        mTvSettleAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectCount == 0) {
                    Toast.makeText(mContext, "请先选择要结算的商品", Toast.LENGTH_SHORT).show();
                } else {
                    List<BeanCart> carts = new ArrayList<>();
                    List<BeanCartChange> beanCartChanges = mAdpRvAtyCart.getBeanCartChanges();
                    for (int i = 0; i < beanCartChanges.size(); i++) {
                        List<BeanCart> beanCarts = beanCartChanges.get(i).getBeanCarts();
                        for (int j = 0; j < beanCarts.size(); j++) {
                            if (beanCarts.get(j).isCheck()) {
                                carts.add(beanCarts.get(j));
                            }
                        }
                    }
                    Collections.reverse(carts);
                    mChanges = new ArrayList<>();
                    changeCartListForSettleAccount(carts);
                    EventBus.getDefault().postSticky(mChanges);
                    Intent intent = new Intent(mContext, AtyBalance.class);
                    startActivityForResult(intent, REQUEST_CODE);

                }
            }
        });
        mCbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                List<BeanCartChange> beanCartChanges = mAdpRvAtyCart.getBeanCartChanges();
                for (int i = 0; i < beanCartChanges.size(); i++) {
                    beanCartChanges.get(i).setCheck(isChecked);
                    List<BeanCart> beanCarts = beanCartChanges.get(i).getBeanCarts();
                    for (int j = 0; j < beanCarts.size(); j++) {
                        beanCarts.get(j).setCheck(isChecked);
                    }
                }
                mAdpRvAtyCart.notifyDataSetChanged();
            }
        });

        mAdpRvAtyCart.setOnSectionItemClickListener(new OnSectionItemClickListener() {
            @Override
            public void onSectionItemClick(int type, int section, int position, int viewID, TextView tv, TextView tvCouponMoney) {
                mSelectCount = 0;
                mNeedMoney = 0;
                mBuyCartIDs.clear();
                if (type == AdpRvAtyCart.CHILD_GOODS_SELECT || type == AdpRvAtyCart.STORE_SELECT) {
                    computeResult();
                }

            }
        });
    }

    private void computeResult() {
        List<BeanCartChange> beanCartChanges = mAdpRvAtyCart.getBeanCartChanges();
        mSelectCount = 0;
        mNeedMoney = 0;
        boolean allIsCheck = true;
        for (int i = 0; i < beanCartChanges.size(); i++) {
            List<BeanCart> beanCarts = beanCartChanges.get(i).getBeanCarts();
            boolean storeIsCheck = true;
            for (int j = 0; j < beanCarts.size(); j++) {
                storeIsCheck = storeIsCheck & beanCarts.get(j).isCheck();
                if (beanCarts.get(j).isCheck()) {
                    mSelectCount += beanCarts.get(j).getCOUNT();
                    mBuyCartIDs.add(beanCarts.get(j).getBUYCAR_ID());
                    mNeedMoney += beanCarts.get(j).getCOUNT() * beanCarts.get(j).getGOODINFO().getSINGLE_PRICE();
                }
            }
            beanCartChanges.get(i).setCheck(storeIsCheck);
            allIsCheck = allIsCheck & beanCartChanges.get(i).isCheck();
        }
        mCbSelectAll.setChecked(allIsCheck);
        mTvSettleAccount.setText("结算  ( " + mSelectCount + " )");
        mTvNeedMoney.setText(CommonsToolsHelper.getTwoDecimal(mNeedMoney) + "");

        //刷新列表 避免Cannot call this method while RecyclerView is computing a layout or scrollin
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setRecode(REFRESH_RV);
        EventBus.getDefault().post(messageEvent);
    }


    HttpOnNextListener<List<BeanCart>> mGetCartListener = new HttpOnNextListener<List<BeanCart>>() {
        @Override
        public void onNext(List<BeanCart> beanCarts) {
            mBeanCartChanges.clear();
            if (beanCarts != null && beanCarts.size() > 0) {
                ArrayList<BeanCartChange> abateGoods = new ArrayList<>();
                for (int i = beanCarts.size() - 1; i > 0; i--) {
                    BeanCart beanCart = beanCarts.get(i);
                    if (beanCart.getGOODINFO().getGOODS_STATUS() == 2) {//失效商品
                        BeanCartChange beanCartChange = new BeanCartChange();
                        beanCartChange.setBUYCAR_ID(beanCart.getBUYCAR_ID());
                        beanCartChange.setGoodsStatus(beanCart.getGOODINFO().getGOODS_STATUS());
                        abateGoods.add(beanCartChange);
                        beanCarts.remove(i);
                    }
                }
                Collections.reverse(beanCarts);
                changeCartList(beanCarts);
                mBeanCartChanges.addAll(abateGoods);
            }
            computeResult();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void changeCartListForSettleAccount(List<BeanCart> beanCarts) {
        BeanCartChange beanCartChange = new BeanCartChange();
        beanCartChange.setStoreName(beanCarts.get(beanCarts.size() - 1).getSTORE_NAME());
        List<BeanCart> carts = new ArrayList<>();
        carts.add(beanCarts.get(beanCarts.size() - 1));
        beanCarts.remove(beanCarts.size() - 1);
        for (int i = beanCarts.size() - 1; i >= 0; i--) {
            if (carts.get(0).getSTORE_NAME().equals(beanCarts.get(i).getSTORE_NAME())) {
                carts.add(beanCarts.get(i));
                beanCarts.remove(beanCarts.get(i));
            }
        }
        beanCartChange.setBeanCarts(carts);
        mChanges.add(beanCartChange);
        if (beanCarts.size() > 0) {
            changeCartListForSettleAccount(beanCarts);
        }
    }

    private void changeCartList(List<BeanCart> beanCarts) {
        BeanCartChange beanCartChange = new BeanCartChange();
        beanCartChange.setStoreName(beanCarts.get(beanCarts.size() - 1).getSTORE_NAME());
        List<BeanCart> carts = new ArrayList<>();
        carts.add(beanCarts.get(beanCarts.size() - 1));
        beanCarts.remove(beanCarts.size() - 1);
        for (int i = beanCarts.size() - 1; i >= 0; i--) {
            if (carts.get(0).getSTORE_NAME().equals(beanCarts.get(i).getSTORE_NAME())) {
                carts.add(beanCarts.get(i));
                beanCarts.remove(beanCarts.get(i));
            }
        }
        beanCartChange.setBeanCarts(carts);
        mBeanCartChanges.add(beanCartChange);
        if (beanCarts.size() > 0) {
            changeCartList(beanCarts);
        }
    }

    private void getData() {
        ApiGetCartList apiGetCartList = new ApiGetCartList(mGetCartListener, mContext, true, false, false);
        HashMap<String, String> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiGetCartList.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetCartList);
    }

    private void initRv() {
        mAdpRvAtyCart = new AdpRvAtyCart(mContext, mBeanCartChanges);
        GridLayoutManager manager = new GridLayoutManager(mContext, 1);
        manager.setSpanSizeLookup(new SectionedSpanSizeLookup(mAdpRvAtyCart, manager));
        mRv.setLayoutManager(manager);
        mRv.setAdapter(mAdpRvAtyCart);
    }

    private void deleteDialog() {
        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
        dialog.setContentView(R.layout.app_dialog_sure_cancel);
        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
        tvContent.setText("确定要删除选中的商品吗?");
        tvCancel.setText("取消");
        tvSure.setText("确定");
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteGoods();
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
    }

    HttpOnNextListener<BaseResultEntity> mDeleteBuyCartListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("删除成功");
            mTvEdit.setVisibility(View.VISIBLE);
            mTvCancel.setVisibility(View.GONE);
            mLlNeedMoney.setVisibility(View.VISIBLE);
            mTvSettleAccount.setVisibility(View.VISIBLE);
            mTvDelete.setVisibility(View.GONE);
            getData();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void deleteGoods() {
        ApiDeleteBuyCart apiDeleteBuyCart = new ApiDeleteBuyCart(mDeleteBuyCartListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        String buyCarID = "";
        for (int i = 0; i < mBuyCartIDs.size(); i++) {
            if (i == mBuyCartIDs.size() - 1) {
                buyCarID += mBuyCartIDs.get(i);
            } else {
                buyCarID += mBuyCartIDs.get(i) + ",";
            }
        }
        map.put("BUYCAR_ID", buyCarID);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiDeleteBuyCart.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiDeleteBuyCart);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            getData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
